package com.hmall.item.interceptor;

import com.hmall.common.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserIdInterceptor implements HandlerInterceptor {
    //前置拦截:登陆用户获取
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头
        String header = request.getHeader("authorization");
        //判断
        if(StringUtils.isBlank(header)){
            //未登陆，抛个403
            log.warn("非法用户访问！请求路径：{}", request.getRequestURI() );
            response.setStatus(403);
            return false;
            /*    throw new RuntimeException("用户未登录");*/
        }
        //转换用户id
        //2、存入ThreadLocal
        BaseContext.setUserId(Long.valueOf(header));
        //3、放行
        return true;
    }

    //最终拦截-----最后，调个方法，做个清理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();
    }
}